package com.wootion.dizhi.timetask;
import com.alibaba.fastjson.JSONObject;
import com.wootion.dizhi.comon.MathParser;
import com.wootion.dizhi.comon.TimeHandler;
import com.wootion.dizhi.dao.TemporaryDao;
import com.wootion.dizhi.dao.WarningMapper;
import com.wootion.dizhi.entity.Config;
import com.wootion.dizhi.entity.Temporary;
import com.wootion.dizhi.entity.Warning;
import com.wootion.dizhi.runData.GlobalData;
import com.wootion.dizhi.runData.ModbusUtil;
import com.wootion.dizhi.service.DataCollectionService;
import com.wootion.dizhi.service.SseService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
@Slf4j
public class TimeTask {


    private String resources = "./data/";
    private Map<String,JSONObject> map = new HashMap<>();
    private String out = "./out/";

    private String runPath = "./run/";

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

    @Resource
    private TemporaryDao temporaryDao;

    @Resource
    TimeHandler timeHandler;

    @Resource
    WarningMapper warningMapper;

    @Resource
    SseService sseService;

    @Resource
    private DataCollectionService dataCollectionService;

    private static final String MQTT_BROKER_URI = "tcp://118.31.248.137:1883";
    //    private static final String MQTT_BROKER_URI = "tcp://localhost:1883";
    private static final String MQTT_CLIENT_ID = UUID.randomUUID().toString();
    private MqttClient mqttClient = new MqttClient(MQTT_BROKER_URI, MQTT_CLIENT_ID);

    public TimeTask() throws MqttException {
    }

    MathParser mathParser = new MathParser();

    //@Scheduled(fixedRate = 6000)
    public void run1() {
        Set<String> devices = GlobalData.DEVICE_IS_RUN.keySet();
        for (String device : devices) {
            String read = "";
            try {
                read = ModbusUtil.read(Integer.valueOf(device));
            } catch (Exception e) {
                GlobalData.DEVICE_IS_RUN.put(device,false);
            }
            Config config = GlobalData.RUN_CONFIG.get(device);
            String string = GlobalData.RUN_DEVICE_DATA.get(device).getString("status");
            //是否推送
            boolean isPush = false;
            if (string.equals("0")){//设备正在记录中
                if (Optional.ofNullable(map.get(device)).isPresent()){
//                判断是否报警
                    JSONObject jsonObject = map.get(device);
                    Double previous = jsonObject.getDouble("data");
                    if (Optional.ofNullable(previous).isPresent()) {
                        if (previous > Double.valueOf(read)) {
                            Warning warning = new Warning();
                            warning.setId(UUID.randomUUID().toString());
                            warning.setMessage("读数异常上升");
                            warning.setAddressExperment(device + config.getExperiment());
                            warning.setCreateTime(new Date());
                            warning.setEnable("0");
                            warning.setIs_read("0");
                            warningMapper.insertWarning(warning);
                            isPush = true;
                        }
                        if (previous == Double.valueOf(read)) {//   当前值和上一个值相同
                            Integer integer = jsonObject.getInteger("index") + 1;
                            jsonObject.put("index", integer);
                            if (integer > 30) {
                                Warning warning = new Warning();
                                warning.setId(UUID.randomUUID().toString());
                                warning.setMessage("读数持续重复");
                                warning.setAddressExperment(device + config.getExperiment());
                                warning.setCreateTime(new Date());
                                warning.setEnable("0");
                                warning.setIs_read("0");
                                warningMapper.insertWarning(warning);
                                isPush = true;
                            }
                        } else {
//                    新增数据
                            jsonObject.put("data", read);
                            jsonObject.put("index", 0);
                            map.put(device, jsonObject);
                        }
                    }
                }

                if (isPush){
                    sseService.sendToAll(dataCollectionService.ceegetwarning());
                }
                String experiment = GlobalData.RUN_CONFIG.get(device).getExperiment();
                Temporary temporary = new Temporary();
                temporary.setAddressExperiment(config.getAddress()+experiment);
                //HH:mm:ss
                temporary.setTime(timeFormat.format(new Date()));
                //yyyy-MM-dd
                temporary.setDate(dateFormat.format(new Date()));
                temporary.setValue(mathParser.parser(Integer.valueOf(read)));
                System.out.println(temporary);
                System.out.println(read);
                System.out.println(mathParser.parser(Integer.valueOf(read)));
                int r = temporaryDao.insert(temporary);
                if(r>0){
                    log.info("液位计数据记录成功");
                }
                if (!Optional.ofNullable(map.get(device)).isPresent()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", read);
                    jsonObject.put("index", 0);
                    map.put(device, jsonObject);
                }
            }
            GlobalData.DEVICE_IS_RUN.put(device,true);

        }


        System.out.println("执行定时任务");
//        System.out.println(timeHandler.toString());
//        Set<String> strings = GlobalData.RUN_DEVICE_DATA.keySet();
//        for (String string : strings) {
//            JSONObject jsonObject1 = GlobalData.RUN_DEVICE_DATA.get(string);
//            Config config = GlobalData.RUN_CONFIG.get(string);
//            Integer status = jsonObject1.getInteger("status");
//            if (status == 0) {
//                Boolean run = getRun(string);
//                if (!run) {
//                    String deviceNo = string.substring(0, string.length() - 1);
//                    String address = string.substring(string.length() - 1, string.length());
//                    List<JSONObject> list1 = getList(deviceNo , address,GlobalData.RUN_CONFIG.get(deviceNo+address).getExperiment());
//                    if (list1.size()==0){
//                        continue;
//                    }
//                    config.setEndTime(list1.get(list1.size()-1).getString("time"));
//                    GlobalData.RUN_CONFIG.put(string,config);
//                    jsonObject1.put("status",2);
//                    System.out.println("设备:"+string+"由于超时未上报,已置为异常中断");
//                    GlobalData.RUN_DEVICE_DATA.put(string,jsonObject1);
//                }
//            }
//        }
    }

//    private Boolean getRun(String deviceNoAndAddress){
//        return timeHandler.isTimeAfterTime(GlobalData.DEVICE_STATUS.get(deviceNoAndAddress),"mm",4);//true在线,false离线
//    };
//    private List<JSONObject> getList(String deviceNo,String address,String experiment) throws IOException {
//        List<JSONObject> list = new ArrayList<>();
//        String content2 = new String(Files.readAllBytes(Paths.get(runPath+deviceNo+address+experiment+".MA")));
//        String[] split = content2.split("OIOAF");
//        if (split.length>0){
//            for (String s : split) {
//                if (!"".equals(s)){
//                    JSONObject jsonObject1 = JSONObject.parseObject(s);
//                    list.add(jsonObject1);
//                }
//            }
//            return list;
//        }else {
//            return list;
//        }
//    }
}

